<?php
namespace app\user\model;
use think\Model;
use think\Request;
use think\exception\HttpException;
use app\common\model\Base;
use app\common\model\ObserviceReciveInterface;
class Auth extends Base{
    protected $table = 'gym_user_info';
    private static $auth_on = true; //是否开启权限验证
    private static $module = []; //当前的模块名称
    private static $controller = []; //当前额控制器名称
    private static $inter_face_mode = false; //是否为接口模式
    private static $group_id = 0; //用户组的id
    private static $group_rule = [];
    public static $roleStock = ['boss'=>1,'fitness'=>2,'member'=>3]; //角色列表： 老板是：1 教练是:2 会员是:3
    protected  function initialize(){
        parent::initialize();
        self::init();
    }

    protected static function init(){
        self::$auth_on = config('auth.auth_on');
        self::$inter_face_mode = config('inter_face_mode');
    }

    /**
     * [getRoleStock 获取角色的信息]
     * @return [type] [description]
     */
    public static function getRoleStock($key=null){
        $roleStock = self::$roleStock;
        if(is_null($key)){
            return $roleStock;
        }

        if(!array_key_exists($key, $roleStock)){
            return false;
        }

        return $roleStock[$key];

    }

    //权限验证
    public static function check($uuid=null){
        $authOn = self::$auth_on;
       // $rootGroup = self::$rootGroup;
        $request = Request::instance();
        //是否开启权限认证
        if(!$authOn){
            return true;
        }
        $moduleControllerAction['module'] = $request->module();
        $moduleControllerAction['controller'] = $request->controller();
        $moduleControllerAction['action'] = $request->action();
        self::resultRule($uuid); //获取全部权限并且赋值
        //超级管理员用户组
        if(self::$group_id == 1){
            return true;
        }
        foreach(self::$group_rule as $val){
            $checkModule = strtoupper($val['module'].'_'.$val['controller'].'_'.$val['action']);
            $checkModuleUser = strtoupper($moduleControllerAction['module'].'_'.$moduleControllerAction['controller'].'_'.$moduleControllerAction['action']);
            if(strcmp($checkModule,$checkModuleUser) === 0){
                return true;
            }
        }
        if(config('auth.auto_error')){
                throw new HttpException(-0002,'没有访问权限！');
            }
        return false;
    }



    //获取用户的权限 ,uuid 可以是当前
    private static function resultRule($uuid=null){
        $result = '';
        $where = [];
        if(empty($uuid) || !preg_match('/\w+/',$uuid)){
            $uuid = '4719aaaa1eba2a7dcd0a868f24b2e3f843b5bca2';
        }
        $where = self::$inter_face_mode?['hash_value'=>$uuid]:['uuid'=>$uuid];
        $result = self::where($where)->alias('u')
        ->join('__AUTH_GROUP_RELATION__ r','u.uuid = r.uid','INNER')
        ->join('__AUTH_GROUP__ g','r.group_id = g.id and g.status = 1')
        ->join('__AUTH_RULE__ e','FIND_IN_SET(g.id,e.group_id)')->field('e.id,e.condition,g.id as group_id,u.uuid,e.controller,e.module,e.action')->select();
        $groupRuleStock = collection($result)->toArray();
        self::$group_id = array_unique(array_column($groupRuleStock,'group_id'))[0];
        self::$group_rule = $groupRuleStock;
        return $groupRuleStock;
    }

    /**
     * [resultRoleInfo 获取用户的角色信息]
     * @return [array] [返回用户的角色信息] 返回是以数组形式进行返回的
     */
    public static function getRoleInfo($uuid = ''){
       $roleStock = self::$roleStock;
        if(empty($uuid)){
            throw new \Exception('返回用户的角色信息错误！');
        }
        $where = ['uid'=>$uuid];
        $field = ['group_id as role'];
        $result = self::table('gym_auth_group_relation')->field($field)->where($where);
        $response  = self::infoOfCache($result);
        if(empty($response)){return false;}
        $roleList = array_intersect($roleStock,array_column($response,'role'));
        //只是返回获取到的键值
        return array_keys($roleList)[0] ;
    }

}
